package cc.linker.steplink.crm.commons.utils;


import org.apache.commons.codec.binary.Base64;

import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.PBEKeySpec;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;

public class AesEncryptUtils {
    private static final String AES = "AES";
    private static final String PADDING = "AES/CBC/PKCS5Padding";
    private static final String KEY_GENERATION_ALG = "PBKDF2WithHmacSHA1";


    private static char[] humanPassphrase = {'P', 'e', 'r', ' ', 'v', 'a', 'l', 'l', 'u', 'm', ' ', 'd', 'u', 'c', 'e', 's', ' ', 'L', 'a', 'b', 'a', 'n', 't'};
    private static byte[] salt = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0xA, 0xB, 0xC, 0xD, 0xE, 0xF};
    private static final int HASH_ITERATIONS = 10000;
    private static final int KEY_LENGTH = 256;

    private static SecretKeySpec secretKeySpec;

    private static byte[] iv = {0xA, 1, 0xB, 5, 4, 0xF, 7, 9, 0x17, 3, 1, 6, 8, 0xC, 0xD, 91};
    private static IvParameterSpec IV = new IvParameterSpec(iv);

    static {
        SecretKey sk = null;
        try {
            SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(KEY_GENERATION_ALG);
            PBEKeySpec keySpec = new PBEKeySpec(humanPassphrase, salt, HASH_ITERATIONS, KEY_LENGTH);
            sk = keyFactory.generateSecret(keySpec);
        } catch (Exception e) {
            e.printStackTrace();
        }
        //noinspection ConstantConditions
        byte[] skAsByteArray = sk.getEncoded();

        secretKeySpec = new SecretKeySpec(skAsByteArray, AES);
    }


    /**
     * 加密
     *
     * @param content 加密的字符串
     */
    public static String encrypt(String content) throws Exception {
        Cipher cipher = Cipher.getInstance(PADDING);
        cipher.init(Cipher.ENCRYPT_MODE, secretKeySpec, IV);
        byte[] b = cipher.doFinal(content.getBytes(StandardCharsets.UTF_8));
        // 采用base64算法进行转码,避免出现中文乱码
        return Base64.encodeBase64String(b);

    }

    /**
     * 解密
     *
     * @param encryptStr 解密的字符串
     */
    public static String decrypt(String encryptStr) throws Exception {
        Cipher cipher = Cipher.getInstance(PADDING);
        cipher.init(Cipher.DECRYPT_MODE, secretKeySpec, IV);
        // 采用base64算法进行转码,避免出现中文乱码
        byte[] encryptBytes = Base64.decodeBase64(encryptStr);
        byte[] decryptBytes = cipher.doFinal(encryptBytes);
        return new String(decryptBytes, StandardCharsets.UTF_8);
    }

    public static void main(String[] args) {
        try {
            System.out.println(encrypt("7532"));
        }catch (Exception e){

        }
    }
}
